<template>
  <div>
    <!-- <searchForm :searchArr="searchArr" @onSubmit="onSubmit"></searchForm> -->
    <div class="gva-table-box">
      <LTable
        tableName="moldStartNotice"
        :pages="pages"
        :columns="columns"
        :tableData="tableData"
        @updateMultipleSelection="updateMultipleSelection"
        @changePages="changePages"
        @rowDblclick="(row) => updateSbuProjectsFunc(row, 1)"
        :maxHeight="'calc(100vh - 226px)'"
        :searchArr="searchArr"
        :isSearch="true"
        @onSubmit="onSubmit"
        :export="true"
      >
        <template #action>
          <div
            class="gva-btn-list"
            v-if="userStore.userInfo.authority?.authorityId !== 1000"
          >
            <el-button type="primary" icon="plus" @click="openDialog"
              >新增</el-button
            >
            <el-button
              icon="delete"
              style="margin-left: 10px"
              v-auth="btnAuth.batchDel"
              :disabled="!multipleSelection.length"
              @click="onDelete"
              >删除</el-button
            >
            <!-- <el-button
                :disabled="multipleSelection.length!=1"
                type="primary"
                icon="edit"
                class="table-button"
                @click="updateSbuProjectsFunc(multipleSelection.length==1&&multipleSelection[0])"
            >
                编辑
            </el-button> -->
            <el-button
              type="primary"
              class="table-button"
              :disabled="multipleSelection.length != 1"
              @click="historyVision"
            >
              历史版本
            </el-button>

            <relatedBtn
              :disabled="multipleSelection.length != 1"
              :row="multipleSelection.length == 1 && multipleSelection[0]"
              :modalType="'moldStartNotice'"
            />
          </div>
        </template>

        <template #q1="{ row }">
          <span>{{
            row.mold_house?.length
              ? formatDate(row.mold_house[0].deliveryDate)
              : ""
          }}</span>
        </template>
        <template #q2="{ row }">
          <span>{{
            row.mold_house?.length && row.mold_house?.length > 1
              ? formatDate(row.mold_house[1].deliveryDate)
              : ""
          }}</span>
        </template>
        <template #q3="{ row }">
          <span>{{
            row.mold_house?.length
              ? formatDate(
                  row.mold_house[row.mold_house.length - 1].deliveryDate
                )
              : ""
          }}</span>
        </template>
        <template #q4="{ row }">
          <span>{{
            row.mold_house?.length
              ? row.mold_house[row.mold_house.length - 1].detailDescription
              : ""
          }}</span>
        </template>
        <template #FirstCreatedAt="{ row }">
          <span v-if="row.FirstCreatedAt">{{formatDate(row.FirstCreatedAt)=="1-01-01" ? '' : formatDate(row.FirstCreatedAt) }}</span>
        </template>
      </LTable>
      <!-- <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div> -->
    </div>
    <el-dialog v-model="historyVisionShow" title="历史版本" width="900">
      <el-table
        ref="multipleTableRef"
        :data="historyList"
        :row-class-name="tableRowClassName"
        @rowDblclick="rowDblclickFun"
        style="width: 100%"
      >
        <el-table-column prop="styleNum" label="款式编号" />
        <el-table-column prop="noticeNum" label="起模单编号" />
        <el-table-column prop="localStyleNum" label="本厂款号" />
        <el-table-column prop="cumstomerNum" label="客户款号" />
        <el-table-column prop="version" label="版本" />
        <el-table-column prop="createdAt" label="创建时间">
          <template #default="scope">
            <span>
              {{ formatDate(scope.row.CreatedAt) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  deleteMoldStartNotice,
  deleteMoldStartNoticeByIds,
  updateMoldStartNotice,
  findMoldStartNotice,
  getMoldStartNoticeList,
  getMoldStartNoticeHistoryList,
} from "@/api/plmMoldStartNotice";
import { useRoute, useRouter } from "vue-router";
// 全量引入格式化工具 请按需保留
import {
  getDictFunc,
  formatDate,
  formatBoolean,
  filterDict,
  ReturnArrImg,
  onDownloadFile,
} from "@/utils/format";
import { useDict } from "@/utils/dictionary";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, watch, onMounted } from "vue";
import dayjs from "dayjs";
// 引入组件
import LTable from "@/components/LTable/LTable.vue";
import { useUserStore } from "@/pinia/modules/user";
// import searchForm from "@/components/searchForm/searchForm.vue";
defineOptions({
  name: "moldStartNotice",
});

// 使用 useRoute 函数获取当前路由信息
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
import { useBtnAuth } from "@/utils/btnAuth";
const btnAuth = useBtnAuth();

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  productSpecNum: "",
  projectNum: "",
  cumstomerNum: "",
  customerStyleNum: "",
  updateUser: "",
  updateTime: new Date(),
  status: "",
});

// 验证规则
const rule = reactive({});

const searchRule = reactive({
  createdAt: [
    {
      validator: (rule, value, callback) => {
        if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
          callback(new Error("请填写结束日期"));
        } else if (
          !searchInfo.value.startCreatedAt &&
          searchInfo.value.endCreatedAt
        ) {
          callback(new Error("请填写开始日期"));
        } else if (
          searchInfo.value.startCreatedAt &&
          searchInfo.value.endCreatedAt &&
          (searchInfo.value.startCreatedAt.getTime() ===
            searchInfo.value.endCreatedAt.getTime() ||
            searchInfo.value.startCreatedAt.getTime() >
              searchInfo.value.endCreatedAt.getTime())
        ) {
          callback(new Error("开始日期应当早于结束日期"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});

const elFormRef = ref();
const elSearchFormRef = ref();
const dict = ref({});

// =========== 表格控制部分 ===========
const tableData = ref([]);
const searchInfo = ref({});
const pages = ref({
  page: 1,
  pageSize: 20,
  total: 0,
});
// ======表格头部数据======
const columns = ref([
  {
    prop: "noticeNum",
    fixedWidth: 130,
    label: "通知单编号",
    show: true, // 通过 show 来控制列的展示或隐藏
    // slot: "noticeNum",
    tableColumnProps: {
      fixed: "left",
    },
    isSearch: true,
    filter: true,
  },
  {
    prop: "styleNum",
    width: 120,
    label: "款式编号",
    show: true, // 通过 show 来控制列的展示或隐藏
  },
  {
    prop: "localStyleNum",
    width: 130,
    label: "本厂款号",
    show: true,
  },
  {
    prop: "customerStyleNum",
    width: 130,
    label: "客户款号",
    show: true,
  },
  {
    prop: "productionDepartment",
    label: "制作部門",
    show: true, // 通过 show 来控制列的展示或隐藏
    fixedWidth: 120,
  },
  {
    prop: "customerDemandDate",
    width: 140,
    label: "客户要求完成",
    show: true,
  },
  {
    prop: "piDemandDate",
    width: 120,
    label: "PI要求完成",
    show: true,
  },
  // {
  //   prop: "transferOrder",
  //   label: "生产地点",
  //   width: 100,
  //   show: true,
  // },
  {
    prop: "CreatedAt",
    width: 120,
    label: "创建时间",
    show: true, // 通过 show 来控制列的展示或隐藏
  },
  {
    prop: "UpdatedAt",
    width: 120,
    label: "更新时间",
    show: true,
  },
  // {
  //   prop: "status",
  //   width: 200,
  //   label: "状态",
  //   show: true,
  // },
  {
    prop: "isMetalPrinted",
    fixedWidth: 100,
    label: "金打印",
    show: true,
  },
  {
    prop: "isSpleenPrinted",
    fixedWidth: 100,
    label: "啤打印",
    show: true,
  },
  {
    prop: "isMetalContained",
    fixedWidth: 100,
    label: "金配件",
    show: true,
  },
  {
    prop: "isSpleenContained",
    fixedWidth: 100,
    label: "啤配件",
    show: true,
  },
  {
    prop: "version",
    fixedWidth: 100,
    label: "版本",
    show: true,
  },
  // 新增付期的四列
  {
    prop: "q1",
    label: "第一次复期",
    show: true,
    fixedWidth: 150,
    slot: "q1",
  },
  {
    prop: "q2",
    label: "第二次复期",
    show: true,
    fixedWidth: 150,
    slot: "q2",
  },
  {
    prop: "q3",
    label: "最后一次复期",
    show: true,
    fixedWidth: 150,
    slot: "q3",
  },
  {
    prop: "q4",
    label: "最后一次复期原因",
    show: true,
    fixedWidth: 150,
    slot: "q4",
  },
  {
    prop: "FirstCreatedAt",
    label:'第一版本创建时间',
    show: true,
    fixedWidth: 150,
    // slot:"FirstCreatedAt"
        },
]);
// ======查询数据======
const searchArr = ref([
  {
    prop: "noticeNum",
    width: 200,
    label: "通知单编号",
    show: true, // 通过 show 来控制列的展示或隐藏
    type: "input",
    value: "",
  },
  {
    prop: "styleNum",
    width: 200,
    label: "款式编号",
    show: true, // 通过 show 来控制列的展示或隐藏
    type: "input",
    value: "",
  },

  {
    prop: "customerDemandDate",
    width: 200,
    label: "客户要求完成",
    show: false,
    type: "datetimerange",
    value: "",
  },
  {
    prop: "piDemandDate",
    width: 200,
    label: "PI要求完成",
    show: false,
    type: "datetimerange",
    value: "",
  },
  // {
  //   prop: "status",
  //   width: 200,
  //   label: "状态",
  //   show: false,
  //   type:'select',
  //   value:'',
  // },
  {
    prop: "isMetalPrinted",
    width: 200,
    label: "金打印",
    show: false,
    type: "select",
    value: "",
    selectList: [
      { value: "1", label: "是" },
      { value: "0", label: "否" },
    ],
  },
  {
    prop: "isSpleenPrinted",
    width: 200,
    label: "啤打印",
    show: false,
    type: "select",
    value: "",
    selectList: [
      { value: "1", label: "是" },
      { value: "0", label: "否" },
    ],
  },
  {
    prop: "isMetalContained",
    width: 200,
    label: "金配件",
    show: true,
    type: "select",
    value: "",
    selectList: [
      { value: "1", label: "是" },
      { value: "0", label: "否" },
    ],
  },
  {
    prop: "isSpleenContained",
    width: 200,
    label: "啤配件",
    show: true,
    type: "select",
    value: "",
    selectList: [
      { value: "1", label: "是" },
      { value: "0", label: "否" },
    ],
  },
  {
    prop: "CreatedAt",
    width: 200,
    label: "创建时间",
    show: true, // 通过 show 来控制列的展示或隐藏
    value: "",
    type: "datetimerange",
    value: "",
  },
  {
    prop: "UpdatedAt",
    width: 200,
    label: "更新时间",
    show: false,
    value: "",
    type: "datetimerange",
    value: "",
  },
  {
    prop: "transferOrder",
    label: "生产地点",
    width: 100,
    show: true,
    value: "",
    type: "input",
  },
  {
    prop: "localStyleNum",
    width: 130,
    label: "本厂款号",
    show: true,
    type: "input",
    value: "",
  },
  {
    prop: "customerStyleNum",
    width: 200,
    label: "客户款号",
    show: true,
    type: "input",
    value: "",
  },

  // 制作部門在onMounted里写了赋值selectList逻辑,请注意
  {
    prop: "productionDepartment",
    label: "制作部門",
    show: true, // 通过 show 来控制列的展示或隐藏
    value: "",
    type: "select",
    selectList: [],
  },
  {
      prop: "FirstCreatedAt",
      label: "第一版创建时间",
      show: true, // 通过 show 来控制列的展示或隐藏
      value: "",
      type: "datetimerange",
    },
]);

// 搜索
const onSubmit = (params) => {
  searchInfo.value = {
    ...params,
  };
  if (
    Array.isArray(searchInfo.value.customerDemandDate) &&
    searchInfo.value.customerDemandDate.length
  ) {
    searchInfo.value.customerDemandStartDate =
      dayjs(
        searchInfo.value.customerDemandDate[0].substr(0, 10) + "00:00:00"
      ).format("YYYY-MM-DDTHH:mm:ssZ") || "";
    searchInfo.value.customerDemandEndDate =
      dayjs(
        searchInfo.value.customerDemandDate[1].substr(0, 10) + "23:59:59"
      ).format("YYYY-MM-DDTHH:mm:ssZ") || "";
    delete searchInfo.value.customerDemandDate;
  }

  if (
    Array.isArray(searchInfo.value.piDemandDate) &&
    searchInfo.value.piDemandDate.length
  ) {
    searchInfo.value.piDemandStartDate =
      dayjs(searchInfo.value.piDemandDate[0].substr(0, 10) + "00:00:00").format(
        "YYYY-MM-DDTHH:mm:ssZ"
      ) || "";
    searchInfo.value.piDemandEndDate =
      dayjs(searchInfo.value.piDemandDate[1].substr(0, 10) + "23:59:59").format(
        "YYYY-MM-DDTHH:mm:ssZ"
      ) || "";
    delete searchInfo.value.piDemandDate;
  }

  pages.value.page = 1;
  pages.value.pageSize = 20;
  getTableData();
};

// 改变页码
function changePages(currentPages) {
  console.log("currentPages=============", currentPages);
  pages.value = {
    ...pages.value,
    ...currentPages,
  };
  getTableData();
}

// 查询
const getTableData = async () => {
  console.log(searchInfo.value);
  const table = await getMoldStartNoticeList({
    page: pages.value.page,
    pageSize: pages.value.pageSize,
    ...searchInfo.value,
  });
  if (table.code === 0) {
    tableData.value = table.data.list;
    tableData.value.forEach((item) => {
      item.CreatedAt = item.CreatedAt ? formatDate(item.CreatedAt) : "";
      item.UpdatedAt = item.UpdatedAt ? formatDate(item.UpdatedAt) : "";
      item.customerDemandDate = item.customerDemandDate
        ? formatDate(item.customerDemandDate)
        : "";
      item.piDemandDate = item.piDemandDate
        ? formatDate(item.piDemandDate)
        : "";
          item.FirstCreatedAt= formatDate(item.FirstCreatedAt)=="1-01-01"
          ? ""
          : formatDate(item.FirstCreatedAt),
      item.isMetalContained = item.isMetalContained == 1 ? "是" : "否";
      item.isMetalPrinted = item.isMetalPrinted == 1 ? "是" : "否";
      item.isSpleenContained = item.isSpleenContained == 1 ? "是" : "否";
      item.isSpleenPrinted = item.isSpleenPrinted == 1 ? "是" : "否";
    });
    pages.value.total = table.data.total;
    pages.value.page = table.data.page;
    pages.value.pageSize = table.data.pageSize;
  }
};

// getTableData();

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {};

// 获取需要的字典 可能为空 按需保留
setOptions();

// 多选数据
const multipleSelection = ref([]);
// 多选
const updateMultipleSelection = (val) => {
  multipleSelection.value = val;
};

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteMoldStartNoticeFunc(row);
  });
};

// 多选删除
const onDelete = async () => {
  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const IDs = [];
    if (multipleSelection.value.length === 0) {
      ElMessage({
        type: "warning",
        message: "请选择要删除的数据",
      });
      return;
    }
    multipleSelection.value &&
      multipleSelection.value.map((item) => {
        IDs.push(item.ID);
      });
    const res = await deleteMoldStartNoticeByIds({ IDs });
    if (res.code === 0) {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      if (tableData.value.length === IDs.length && pages.value.page > 1) {
        pages.value.page--;
      }
      getTableData();
    }
  });
};

// 删除行
const deleteMoldStartNoticeFunc = async (row) => {
  const res = await deleteMoldStartNotice({ ID: row.ID });
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    if (tableData.value.length === 1 && pages.value.page > 1) {
      pages.value.page--;
    }
    getTableData();
  }
};

function detailSbuProjectsFunc(params) {
  console.log(params);
}

// 打开弹窗
const openDialog = () => {
  router.push({
    path: "/layout/moldStartNoticeAdd",
  });
};

function updateSbuProjectsFunc(datas, isView) {
  router.push({
    path: `/layout/moldStartNoticeAdd`,
    query: { ID: datas.ID, subTitle: datas.noticeNum, isView: isView },
  });
}

// 历史版本shou
const historyVisionShow = ref(false);
let historyList = ref([]); // 历史版本数据
// 历史版本
const historyVision = () => {
  historyList.value = [];
  let sel = multipleSelection.value[0];
  historyVisionShow.value = true;
  getMoldStartNoticeHistoryList({ noticeNum: sel.noticeNum }).then((res) => {
    if (res.code == 0) {
      historyList.value = res.data.list;
    }
  });
};
const rowDblclickFun = (row, column) => {
  historyVisionShow.value = false;
  if (row.ID == historyList.value[0].ID) {
    router.push({
      path: `/layout/moldStartNoticeAdd`,
      query: { ID: row.ID, subTitle: row.noticeNum, isView: 1 },
    });
  } else {
    router.push({
      path: `/layout/moldStartNoticeAdd`,
      query: {
        ID: row.ID,
        noticeNum: row.noticeNum,
        subTitle: row.noticeNum,
        isView: 1,
        version: row.version || "暂无",
        isBigVersion: row.index === 0 ? 1 : 0,
      },
    });
  }
};

const tableRowClassName = ({ row, rowIndex }) => {
  row.index = rowIndex;
};
onMounted(async () => {
  dict.value = await useDict("noticeProductionDepartment");
  searchArr.value[searchArr.value.length - 1].selectList =
    dict.value.noticeProductionDepartment;
});
watch(
  () => route.path,
  (newPath, oldPath) => {
    //   console.log('路由已变更：', `从 ${oldPath} 到 ${newPath}`);
    if (newPath == "/layout/moldStartNotice") {
      getTableData();
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
</style>
